/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package share;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mire
 */
public class AliveCheckThread implements Runnable {

    private ConcurrentHashMap<Integer, Server> servers;
    private int port;
    private String backupFile;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");

    public AliveCheckThread(ConcurrentHashMap<Integer, Server> servers, int port, String backupFile) {
        this.servers = servers;
        this.port = port;
        this.backupFile = backupFile;
    }

    @Override
    public void run() {
        String threadInfo = dateFormat.format(new Date()) + " ";
        System.out.println(threadInfo + "Alive check started...");
        boolean error = false;
        Collection<Server> values = servers.values();
        int size = values.size();
        for (Iterator<Server> it = values.iterator(); it.hasNext() && size != 0; size--) {
            Server s = it.next();

            boolean onLine = true;
            String IPAddress = s.getAddress();
            SocketCommunicator c = null;

            try {
                if (IPAddress.equals(InetAddress.getLocalHost().getHostAddress())) {
                    continue;
                }

                if (!s.isOnline()) {
                    continue;
                }

                int currentPort = (port != 0) ? port : s.getCentralPort();

                c = new SocketCommunicator(new Socket(IPAddress, currentPort));
                c.open();

                c.writeString("ALIVE");
                if (!c.readString().equals("YES")) {
                    onLine = false;
                }

            } catch (UnknownHostException ex) {
                Logger.getLogger(AliveCheckThread.class.getName()).log(Level.SEVERE, null, ex);
                onLine = false;
            } catch (IOException ex) {
                Logger.getLogger(AliveCheckThread.class.getName()).log(Level.SEVERE, null, ex);
                onLine = false;
            } finally {
                if (c != null) {
                    try {
                        c.close();
                    } catch (IOException ex) {
                        Logger.getLogger(AliveCheckThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            s.setOnline(onLine);
            error = onLine ? error : true;
            System.out.println(threadInfo + s.getAddress() + " " + (onLine ? "ALIVE" : "DEAD"));
        }       
    }
}
